﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace NDF.Web.Mvc.UI.EasyUI
{
    public static class EasyUiFactoryExtensions
    {
        public static MvcHtmlString EasyUiHelper(this EasyUiFactory factory, EasyUiType uiType, ModelMetadata metadata,
            string name, object value, bool useViewData,
            object dataOptions, object htmlAttributes, bool setId = false, string innerHtml = null)
        {
            HtmlHelper htmlHelper = factory.Html;
            string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            if (String.IsNullOrEmpty(fullName))
            {
                throw new ArgumentException("值不能为 null 或空字符串.", "name");
            }

            ModelState modelState;
            object valueParameter = value;
            if (useViewData && htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState != null && modelState.Value != null)
            {
                valueParameter = modelState.Value.RawValue;
            }

            EasyUiBuilder builder = new EasyUiBuilder
            {
                Type = uiType,
                Name = fullName,
                DataOptions = dataOptions,
                HtmlAttributes = htmlAttributes,
                InnerHtml = innerHtml,
                SetId = setId,
                Value = valueParameter
            };

            TagBuilder tagBuilder = builder.GetTagBuilder();
            htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);
            var isSelfClosing = HtmlUtils.IsSelfClosingTag(tagBuilder.TagName);
            var html = tagBuilder.ToString(isSelfClosing ? TagRenderMode.SelfClosing : TagRenderMode.Normal);
            return MvcHtmlString.Create(HttpUtility.HtmlDecode(html));
        }
    }
}
